package com.example.sunsg.okhttptest.util;

import android.app.Activity;
import android.view.View;

import com.example.sunsg.okhttptest.cuseomannotation.LayoutAnnotation;
import com.example.sunsg.okhttptest.cuseomannotation.ViewAnnotation;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by NOTE-026 on 2016/7/20.
 */
public class AnnotationUtil {
    /**
     * 布局文件的注解解析
     * @param activity
     */
    public static void injectionLayout(Activity activity){
        Class<? extends Activity> classBean = activity.getClass();
        if(classBean.isAnnotationPresent(LayoutAnnotation.class)){
            LayoutAnnotation layoutAnnotation = classBean.getAnnotation(LayoutAnnotation.class);
            int layoutId = layoutAnnotation.value();
//            activity.setContentView(layoutId);
            try {
                Method method = classBean.getMethod("setContentView",int.class);
                method.invoke(activity,layoutId);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * view的注解解析
     * @param object
     */
    public static void injectionView(Object object){
        Class classBean = object.getClass();
        Field[] fields = classBean.getDeclaredFields();
        for (Field field : fields){
            if(field.isAnnotationPresent(ViewAnnotation.class)){
                ViewAnnotation viewAnnotation = field.getAnnotation(ViewAnnotation.class);
                int viewId = viewAnnotation.value();
                try {
                    Method method = classBean.getMethod("findViewById",int.class);
                    Object view = method.invoke(object,viewId);
                    field.setAccessible(true);
                    field.set(object, view);
//
//                    field.setAccessible(true);
//                    field.set(activity,activity.findViewById(viewId));
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
